package com.liull.netty.sanshengshui.first_example;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 15:31 2021/4/29
 * @Modified By:
 */
public class ServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 1.客户端发送消息为空 提示please type something
        if (StrUtil.isBlank(msg)) {
            ctx.writeAndFlush("please type something");
        } else if ("bye".equalsIgnoreCase(msg)) {
            // 直接close会导致关不掉
            // ctx.close();
            ctx.writeAndFlush("Bye bye!").addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.writeAndFlush("Do you say " + msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("welcome to " + ctx.channel().localAddress() + " it is " + LocalDateTime.now().format(
                DateTimeFormatter.ofPattern(DatePattern.CHINESE_DATE_TIME_PATTERN)));
    }
}
